<!--
 * 登录页
 * @author: 
 * @since: 2024-11-24
 * Login.vue
-->
<template>
  <div class="body">
    <div class="loginbox">
      <div class="top">
        <img class="logoImg" src="@/assets/images/logo.png" />
        <p class="title margin-t-2">{{ configKey.name }}</p>
        <p class="slogan margin-t-2">{{ configKey.slogan }}</p>
      </div>
      <div class="main padding-l-2 padding-r-2">
        <div class="login-title">用户登录</div>
        <div class="login-view">
          <a-form ref="formRef" :model="form" :rules="rules">
            <a-form-item name="username">
              <a-input
                size="large"
                v-model:value="form.username"
                placeholder="请输入账户"
                allow-clear
              >
                <template #prefix>
                  <span class="iconfont icon-yonghuming"></span>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item name="password">
              <a-input-password
                size="large"
                v-model:value="form.password"
                placeholder="请输入密码"
                autocomplete
                allow-clear
              >
                <template #prefix>
                  <span class="iconfont icon-mima"></span>
                </template>
              </a-input-password>
            </a-form-item>
            <!-- <a-form-item name="code">
              <a-input size="large" v-model:value="form.code" placeholder="请输入验证码" allow-clear>
                <template #prefix>
                  <span class="iconfont icon-yanzhengma"></span>
                </template>
              </a-input>
              <img v-show="code" :src="code" alt="" class="code margin-l-1" @click="getCode()" />
            </a-form-item> -->
            <!-- <a-form-item name="name">
              <a-checkbox v-model:checked="form.rememberPwd">记住密码</a-checkbox>
            </a-form-item> -->
          </a-form>
          <a-button
            size="large"
            class="sumbit margin-t-2"
            type="primary"
            :loading="userStore.isLogining"
            @click="login"
          >
            {{ userStore.isLogining ? "登录中" : "确定" }}
          </a-button>
        </div>
      </div>
    </div>
  </div>
  <div class="foot-bar">{{ configKey.copyright }}</div>
</template>

<script setup>
import router from "@/router";
import { useRoute } from "vue-router";
import { encrypt } from "@/utils/jsencrypt";
import auth from "@/api/auth";
import CryptoJS from "crypto-js";
import Cookies from "js-cookie";

// 状态管理依赖
import { useUserStore } from "@/store/modules/user";
sessionStorage.setItem("accessToken", "");
sessionStorage.setItem("tagsView", "");

const userStore = useUserStore();
const route = useRoute();

const form = reactive({
  username: "",
  password: "",
  uuid: "",
  code: "",
  rememberPwd: false,
});
const rules = reactive({
  username: [{ required: true, message: "账户不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});

// let code = ref('')
const formRef = ref();
let configKey = ref({ name: "数智化管理协同办公平台", logo: "" });

// const getCode = () => {
//   auth.code().then((res) => {
//     code.value = 'data:image/png;base64,' + res.data.img
//     form.uuid = res.data.uuid
//   })
// }
const login = () => {
  formRef.value.validate().then(() => {
    console.log("通过");

    const param = {
      username: form.username,
      password: encrypt(form.password.trim()),
      uuid: form.uuid,
      code: form.code,
    };
    userStore.setIsLogining(true);
    auth
      .login(param)
      .then((res) => {
        console.log("res:", res);
        // let routers = router.getRoutes();
        // routers.map((it) => {
        //   if (it.name) {
        //     if (
        //       ![
        //         "Login",
        //         "Dashboard",
        //         "MainPage",
        //         "Error",
        //         "404",
        //         "NotFound",
        //       ].includes(it.name)
        //     ) {
        //       router.removeRoute(it.name);
        //     }
        //   }
        // });
        userStore.login(res.data.access_token);
        const query = route.query;
        const redirect = query.redirect || "/";
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        // 登录时，记住密码,加密
        if (form.rememberPwd) {
          Cookies.set("username", form.username, {
            expires: 30,
          });
          // 加密，12345678521为密钥
          Cookies.set(
            "password",
            CryptoJS.AES.encrypt(form.password, "12345678521", {
              expires: 30,
            })
          );
        } else {
          Cookies.remove("username");
          Cookies.remove("password");
        }
        console.log("redirect:", redirect);
        console.log("otherQueryParams:", otherQueryParams);

        router.push({ path: redirect, query: otherQueryParams }); //跳转后跳到重定向页或首页
      })
      .catch(() => {
        // getCode()
        form.code = "";
        userStore.setIsLogining(false);
      });
  });
};
// 获取验证码
// getCode()
// 获取版权、Logo等配置信息
if (!userStore.configKey || !Object.keys(userStore.configKey).length) {
  userStore.getConfigKey().then((res) => {
    configKey.value = res.value;
  });
}
// 回车查询数据
const keyupSubmit = (e) => {
  if (e.key === "Enter" && route.path === "/login") {
    login();
  }
};
onMounted(() => {
  // 判断是否有记住密码
  if (Cookies.get("password")) {
    form.username = Cookies.get("username");
    form.password = CryptoJS.AES.decrypt(
      Cookies.get("password"),
      "12345678521"
    ).toString(CryptoJS.enc.Utf8);
  } else {
    form.username = "";
    form.password = "";
  }
  window.addEventListener("keydown", keyupSubmit, true); //开启监听键盘按下事件
});
</script>

<style scoped lang="less">
@loginbox-width: 800px;
@loginbox-height: 580px;
@loginbox-image-width: 355px;

.body {
  width: 100%;
  min-width: 1200px;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #cdcdcd;
  background: url("@/assets/images/bg.jpg") 100% 100%;

  .loginbox {
    z-index: 99;
    width: @loginbox-width;
    height: @loginbox-height;
    margin: auto;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
    .top {
      text-align: center;
      width: @loginbox-image-width;
      height: 100%;
      background-size: 100%;
      background: url("@/assets/images/bg_inner.png") center;
      float: left;
      .logoImg {
        height: var(--layout-header-height);
        vertical-align: top;
        margin: 170px auto 10px;
      }
      .title {
        font-size: 24px;
        color: #fff;
        font-family: Avenir, "Helvetica Neue", Arial, Helvetica, sans-serif;
        font-weight: 600;
      }
      .slogan {
        font-size: 16px;
        color: #fff;
        font-family: Avenir, "Helvetica Neue", Arial, Helvetica, sans-serif;
        font-weight: 600;
      }
    }
    .main {
      width: calc(@loginbox-width - @loginbox-image-width - 20px);
      margin: 0 auto;
      float: left;
      display: block;
      position: relative;
      box-sizing: border-box;
      .login-title {
        text-align: center;
        font-size: 16px;
        color: #000;
        padding: 64px 0;
      }
      :deep(.arco-form-item) {
        flex-wrap: wrap;
        margin-top: 12px;
      }
      .code {
        width: 107px;
        height: 39px;
        cursor: pointer;
        border: 1px solid #cdcdcd;
        box-sizing: border-box;
      }
      .sumbit {
        width: 100%;
      }
    }
  }
}
.foot-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: var(--layout-footer-height);
  color: #000;
}
</style>
